#!/usr/local/bin/ruby
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'utf8'

u = 1.25*10**7
K = 5

def N(pro, k)
  pro/(1-pro) -(k+1)*pro**(k+1)/(1-pro**(k+1))
end

def leff(l, pro, k)
 l*(1-(1-pro)*pro**k/(1-pro**(k+1)))
end

def T(n,l)
  n/l
end

def pk(pro,k)
  (1-pro)*pro**k/(1-pro**(k+1))
end

#l=[0.3,0.3, 0.25, 0.3,0.2,0.25,0.2,0.2,0.2,0.7, 0.7, 0.2, 0.8, 0.8]

def get_t_by_constant_packets(packets, pros,u, k)
  delay_tot = 0.0
  l_tot=0.0
  packets.each_with_index do |packet, index|
    tot = 0.0
    pros[index].each do |i|
      pro = i
      n = N(pro,k)
      le = leff(i*u,pro,k)
      t = T(n,le)
      tot += t
    end
    delay_tot += tot*packet
    l_tot += packet
  end
  delay_tot/l_tot
end

def get_t_by_change_packets(packets, pros,u, k)
  delay_tot = 0.0
  l_tot=0.0
  packets.each_with_index do |packet, index|
    tot = 0.0
    new_packet=packet
    tot_packets = 0
    pros[index].each do |i|
      pro = i
      n = N(pro,k)
      le = leff(i*u,pro,k)
      t = T(n,le)

      new_packet = get_packets_by_lost(pro, k, new_packet) if index!=0

      tot += t*new_packet
      tot_packets +=new_packet
    end

    delay_tot += tot
    l_tot += tot_packets*1.0/pros[index].length

  end
  delay_tot/l_tot
end


def get_pro(pro, k)
  (1-pk(pro,k))*pro
end

def get_packets_by_lost(pro, k, packet)
  (1-pk(pro,k))*packet
end

a1b2 = get_pro(0.3, K)

b2a4 = get_pro(a1b2+0.25, K)

b1b3 = get_pro(0.2, K)

b3a4 = get_pro(b1b3+0.2, K)

a4 = get_pro(b2a4+b3a4, K)

b1c3 = get_pro(0.7,K)

c3 = get_pro(b1c3, K)

a3a2 = get_pro(0.8, K)

a2 = get_pro(a3a2, K)

packets=[0.3, 0.25, 0.2, 0.7, 0.2, 0.8]
pros = [
  [a1b2, b2a4, a4],
  [b2a4, a4],
  [b1b3, b3a4, a4],
  [b1c3, c3],
  [b3a4, a4],
  [a3a2, a2]
]

p get_t_by_constant_packets(packets, pros, u, K)
p get_t_by_change_packets(packets, pros, u, K)

